package com.ling.algorithm;

import java.util.Random;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.function.Function;
import java.util.function.Supplier;

public class CompletableFutureDemo {

    public static void main(String[] args) {

        //thenApply
        /**
         * thenApply转换的是泛型中的类型，返回的是同一个CompletableFuture
         */
//        CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
//            int result = 100;
//            System.out.println("第一次运算" + result);
//            return result;
//        }).thenApply(number -> {
//            int result = number * 5;
//            System.out.println("第二次运算" + result);
//            return result;
//        });

        //thenCompose
        /**
         * thenCompose将内部的CompletableFuture调用展开来并使用上一个CompletableFutre调用的结果在下一步的CompletableFuture调用中进行运算，是生成一个新的CompletableFuture。
         */
//        CompletableFuture<Integer> future = CompletableFuture.supplyAsync(
//            new Supplier<Integer>() {
//                @Override
//                public Integer get() {
//                    int number = new Random().nextInt(30);
//                    System.out.println("第一次运算" + number);
//                    return number;
//                }
//            }
//        ).thenCompose(new Function<Integer, CompletionStage<Integer>>() {
//            @Override
//            public CompletionStage<Integer> apply(Integer param) {
//                return CompletableFuture.supplyAsync(new Supplier<Integer>() {
//                    @Override
//                    public Integer get() {
//                        int number = param * 2;
//                        System.out.println("第二次运算：" + number);
//                        return number;
//                    }
//                });
//            }
//        });

        test02();
    }

    public static void test02() {
        ExecutorService threadPool = Executors.newFixedThreadPool(5);       //定长线程池
        try { //对线程进行执行十条打印任务
            for (int i = 1; i <= 10; i++) {
                threadPool.execute(() -> {
                    System.out.println(Thread.currentThread().getName() + "=>执行完毕！");
                });
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //用完线程池一定要记得关闭
            threadPool.shutdown();
        }
    }
}
